﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using MassPokerTool.Infrastructure.Hooking.Data;

namespace MassPokerTool.Infrastructure.Hooking.Filters
{
    public class ScreenCaptureBitBltHookFilter : IBitBltFilter
    {
        public bool Match(IntPtr hdcDest, int xDest, int yDest, int wDest, int hDest, IntPtr hdcSource, int xSrc, int ySrc, int rasterOp, out IHookData hookData)
        {
            hookData = new PokerStarsChatBitBltHookData();
            var hWnd = PlatformInvoke.WindowFromDC(hdcDest);
            var className = new StringBuilder(100);
            PlatformInvoke.GetClassName(hWnd, className, className.Capacity);
            
            var parentHWnd = PlatformInvoke.GetParent(hWnd);
            var windowText = new StringBuilder(100);
            PlatformInvoke.GetWindowText(parentHWnd, windowText, windowText.Capacity);
            var myhMemDc = PlatformInvoke.CreateCompatibleDC(hdcSource);
            var myhBitmap = PlatformInvoke.CreateCompatibleBitmap(hdcSource, wDest, hDest);
            var myhOld = PlatformInvoke.SelectObject(myhMemDc, myhBitmap);
            PlatformInvoke.BitBlt(myhMemDc, 0, 0, wDest, hDest, hdcSource, 0, 0, PlatformInvoke.Srccopy);
            var bmp = Image.FromHbitmap(myhBitmap);

            byte[] byteArray;
            using (var ms = new MemoryStream())
            {
                bmp.Save(ms, ImageFormat.Bmp);
                byteArray = ms.ToArray();
            }

            hookData = new ScreenCaptureBitBltHookData()
                           {
                               WindowName = windowText.ToString(),
                               SerializedBmp = byteArray
                           };
            PlatformInvoke.SelectObject(myhMemDc, myhOld);
            PlatformInvoke.DeleteDC(myhMemDc);
            PlatformInvoke.DeleteObject(myhBitmap);
            return true;
        }
    }
}
